import { createApp, type VNode, type App, h } from "vue";
import { ElConfigProvider } from "element-plus";
import { zhCn } from "element-plus/es/locales.mjs";

export class ComponentHelper {
  #app: App;
  #container: HTMLDivElement;
  #parentDiv: HTMLElement;
  private constructor(
    component: () => VNode,
    parent?: HTMLDivElement | string
  ) {
    // 创建 Vue 应用
    this.#app = createApp(h(ElConfigProvider, { locale: zhCn }, component));
    // 获取父级容器
    if (!parent) this.#parentDiv = document.body;
    else if (typeof parent === "string") {
      this.#parentDiv = document.querySelector(parent) || document.body;
    } else this.#parentDiv = parent;
    // 创建容器
    this.#container = document.createElement("div");
    // 将容器添加到父元素中
    this.#parentDiv.appendChild(this.#container);
    // 挂载
    this.#app.mount(this.#container);
  }
  /**
   * 挂载函数组件
   * @param component 组件
   * @param parent divDom 或 Slelctor 默认 document.body
   * @returns  组件实例
   */
  static mount = (component: () => VNode, parent?: HTMLDivElement | string) => {
    return new ComponentHelper(component, parent);
  };

  /** 获取容器 */
  getContainer() {
    return this.#container;
  }

  /** 卸载组件 */
  unmount() {
    // 卸载
    this.#app.unmount();
    // 移除容器
    this.#parentDiv.removeChild(this.#container);
  }
}
